import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.ServletException;
import java.io.File;

/**
 * @author yk
 * @date 2021/2/23 16:37
 * @description
 */
public class SpringBootYanApplication {

    public static void main(String[] args) throws ServletException, LifecycleException {
        SpringBootYanApplication.run(SpringBootYanApplication.class,args);
    }

    private static void run(Class<SpringBootYanApplication> springBootYanApplicationClass, String[] args) throws ServletException, LifecycleException {

        //创建Tomcat服务器
        Tomcat tomcatServer = new Tomcat();
        //指定端口号
        tomcatServer.setPort(8080);
        //读取项目路径 加载静态资源
        StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/",new File("src/main").getAbsolutePath());
        //禁止重新载入
        ctx.setReloadable(false);
        //class文件地址
        File file = new File("target/classes");
        //创建webRoot
        WebResourceRoot resource = new StandardRoot(ctx);
        //Tomcat内部读取class执行
        resource.addJarResources(new DirResourceSet(resource,"/WEB-INF/classes",file.getAbsolutePath(),"/"));
        //启动Tomcat
        tomcatServer.start();
        System.out.println("Tomcat服务启动成功");
        //异步接收请求
        tomcatServer.getServer().await();
    }
}
